import Swal, { SweetAlertOptions } from "sweetalert2";
import { store } from "@/store/index";

import LangConst from "@/common/constants/LangConst";

const SweetAlertService = {
  success(title?: string, message?: string) {
    return Swal.fire({
      icon: "success",
      title: title,
      text: message,
    });
  },
  error(title?: string, message?: string) {
    return Swal.fire({
      icon: "error",
      title: title,
      text: message,
    });
  },
  info(title?: string, message?: string) {
    return Swal.fire({
      icon: "info",
      title: title,
      text: message,
    });
  },
  warning(title?: string, message?: string) {
    return Swal.fire({
      icon: "warning",
      title: title,
      text: message,
    });
  },
  async question(title: string, text: string) {
    const res = await Swal.fire({
      icon: "question",
      title: title,
      text: text,
      showCancelButton: true,
      reverseButtons: false,
      confirmButtonColor: "#3876ab",
      cancelButtonText: store.getters.t(LangConst.Btn.Cancel),
      confirmButtonText: store.getters.t(LangConst.Btn.Confirm),
    });
    return res.value;
  },
  fire(options: SweetAlertOptions) {
    return Swal.fire(options);
  },
  test() {
    Swal.fire({
      title: "Submit your Github username",
      input: "text",
      inputAttributes: {
        autocapitalize: "off",
      },
      showCancelButton: true,
      confirmButtonText: "Look up",
      showLoaderOnConfirm: true,
      preConfirm: (login: any) => {
        return fetch(`//api.github.com/users/${login}`)
          .then((response: any) => {
            if (!response.ok) {
              throw new Error(response.statusText);
            }
            return response.json();
          })
          .catch((error: any) => {
            Swal.showValidationMessage(`Request failed: ${error}`);
          });
      },
      allowOutsideClick: () => !Swal.isLoading(),
    }).then((result: any) => {
      if (result.value) {
        Swal.fire({
          title: `${result.value.login}'s avatar`,
          imageUrl: result.value.avatar_url,
        });
      }
    });
  },
};

export default SweetAlertService;
